<?php
namespace app\back\controller;

use \app\common\libs\WeixinHelper;
use \app\back\model\Account;

class Login extends \think\Controller {
	function weixin($code='') {

		if(!empty($code)) {
			$appid = config('weixin.appid');
			$secret = config('weixin.appsecret');
			$access_token = WeixinHelper::getWebAccessTokenByCode($appid, $secret, $code);

			$userinfo =Account::where('wx_openid', $access_token['openid'])->field('mobile,role')->find();

			if(is_null($userinfo))
				goto gosubscribe;

			session('userinfo.role', $userinfo->role);
			session('userinfo.openid', $access_token['openid']);
			session('userinfo.mobile', $userinfo->mobile);
			session('userinfo.login_from', 'weixin');
			
			if($userinfo->role === 99) {
				$this->redirect('back/index/index');
			} else {
				// 跳往用户中心
				$this->redirect('index/member/index');
			}

			gosubscribe:
			$this->success('您还不是会员，请关注公众号，开通会员再来试试吧', config('weixin.subscribe_course'));
		}

	}

	function login() {
		if(session('?userinfo.mobile')) {
			$this->redirect('back/index/index');
		}

		$account_model = new \app\back\model\Account;
		if(request()->isPost()) {
			$account_model->mobile = input('post.')['user']['email'];
			$userinfo = $account_model->where('mobile', $account_model->mobile)
							->field('password, role, wx_openid')->find();

			if(!$userinfo) {
				$account_model->message = '帐号不存在';
				goto gologin;
			}

			if($userinfo->role !== 99) {
				$account_model->message = '无权登录';
				goto gologin;
			}

			$password = md5('yiyi'.md5(input('post.')['user']['password']).'yaya');
			if($userinfo->password !== $password) {
				$account_model->message = '密码错误';
				goto gologin;
			}

			if($userinfo) {
				session('userinfo.role', 99);
				session('userinfo.mobile', input('post.')['user']['email']);
				session('userinfo.openid', $userinfo->wx_openid);
				session('userinfo.login_from', 'web');

				$this->redirect('back/index/index');
			}
		}

		gologin:

		return $this->fetch('', ['model'=>$account_model]);
	}
}